// @ts-nocheck
import { chromium } from 'playwright';
import { $fetch } from './utils/fetchIndex';

(async () => {
  try {
    // 1. 启动环境、获取连接
    const id = '03a55b98d1eb438aaf9d03c6ff03bfd5';
    const res = await $fetch(`http://127.0.0.1:50213/api/v2/browser/start?account_id=${id}`);

    console.log(res);
    var browserUrl;
    if (res.status !== 0) {
      browserUrl = `http://${res.data.ws.selenium}`;
      console.log('连接获取成功--')
    } else {
      console.log('获取失败:')
      return;
    }

    // 2. 创建浏览器实例和页面
    let browser, context, page;
    console.log('连接到_browserUrl_:', browserUrl)
    browser = await chromium.connectOverCDP(browserUrl);
    context = browser.contexts()[0];
    page = await context.newPage();

    // 设置一个等待时间变量
    let waitTime = Math.floor(Math.random() * (5000 - 500 + 1)) + 500;

    waitTime = Math.floor(Math.random() * (1000 - 888 + 1)) + 1500;
    console.log(`等待时间888~1000--${waitTime}:${new Date().toLocaleString()}`);
    await page.waitForTimeout(waitTime);

    console.log(`新建标签:${new Date().toLocaleString()}`);
    await page.evaluate(() => {
      window.open('', '_blank')
    });

    console.log(`关闭其他标签:${new Date().toLocaleString()}`);
    // 获取所有页面
    const pages = await page.context().pages();
    // 关闭其他标签
    for (const p of pages) {
      if (p !== page) {
        await p.close()
      }
    }

    waitTime = Math.floor(Math.random() * (1000 - 888 + 1)) + 1500;
    console.log(`等待时间888~1000--${waitTime}:${new Date().toLocaleString()}`);
    await page.waitForTimeout(waitTime);

    console.log(`访问页面--${waitTime}:${new Date().toLocaleString()}`);
    // await page.goto(`https://www.ygg.re/`, { waitUntil: 'networkidle' });
    await page.goto(`https://www.browserscan.net/zh/bot-detection/`, {timeout: 180000});

    waitTime = Math.floor(Math.random() * (1000 - 888 + 1)) + 360000;
    console.log(`等待时间888~1000--${waitTime}:${new Date().toLocaleString()}`);
    await page.waitForTimeout(waitTime);

  } catch (error) {
    console.error('失败:', error);
    process.exit(1); // 非零退出码表示程序异常终止
  }
})();

// npx ts-node main.ts